package cn.bellychang.wangzheng.queue;

import cn.bellychang.bobo.queue.Queue;

/**
 * @author ChangLiang
 * @date 2021/1/28
 */
public class QueueBasedOnLinkedList<E> implements Queue<E> {

    private int count;

    private Node<E> head = null;

    private Node<E> tail = null;

    @Override
    public int getSize() {
        return count;
    }

    @Override
    public boolean isEmpty() {
        return count==0;
    }

    @Override
    public void enqueue(E e) {
        if (count == 0) {
            head = new Node<>(e, null);
            tail = head;
        } else {
            Node<E> temp = tail;
            tail = new Node<>(e, null);
            temp.next = tail;
        }
        count++;
    }

    @Override
    public E dequeue() {
        if (count == 0) {
            throw new RuntimeException("queue is empty");
        }
        Node<E> temp = head;
        head = head.next;
        count--;
        return temp.data;
    }

    @Override
    public E getFront() {
        if (count == 0) {
            throw new RuntimeException("queue is empty");
        }
        return head.data;
    }

    private static class Node<E> {
        E data;
        Node<E> next;

        public Node(E data, Node<E> next) {
            this.data = data;
            this.next = next;
        }

    }

    @Override
    public String toString() {
        E[] tempArr = (E[]) new Object[count];
        Node<E> temp = head;
        int index = count - 1;
        while (temp != null) {
            tempArr[index] = temp.data;
            temp = temp.next;
            index--;
        }

        StringBuilder builder = new StringBuilder();
        builder.append("Queue Tail {");

        for (int i=0; i<tempArr.length; i++) {
            builder.append(tempArr[i]).append("->");
        }
        return builder.toString().endsWith("->") ?
                builder.substring(0, builder.length() - 2) + "} Head" :
                builder.append("} Head").toString();
    }
}
